package com.slipper.common.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.slipper.common.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.slipper.common.zxing.MatrixToImageWriter;

public class QrCodeUtil {
    private static final Logger logger = LoggerFactory.getLogger(QrCodeUtil.class);
    
    // 图片宽度的一般  
    private static final int IMAGE_WIDTH = 80;
    private static final int IMAGE_HEIGHT = 80;
    private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
    private static final int FRAME_WIDTH = 2;
    
    /**
     * 获取图片二维码
     */
    public static String decode(InputStream inputStream) {
        logger.debug("解释二维码开始...");
        String contents = null;
        MultiFormatReader formatReader = new MultiFormatReader();
        BufferedImage image;
        try {
            image = ImageIO.read(inputStream);
            
            // 将图像数据转换为1 bit data
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            // BinaryBitmap是ZXing用来表示1 bit data位图的类，Reader对象将对它进行解析
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            
            Map<DecodeHintType, String> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            
            // 对图像进行解码
            Result result = formatReader.decode(binaryBitmap, hints);
            contents = result.toString();
        } catch (Exception e) {
            logger.error("解码出错！", e);
        }
        logger.debug("解释二维码结束：" + contents);
        return contents;
    }
    
    /**
     * 获取图片二维码
     */
    public static String decode(String filePath) {
        return decode(new File(filePath));
    }
    
    /**
     * 获取图片二维码
     */
    public static String decode(File file) {
        logger.debug("解释二维码文件开始...");
        String contents = null;
        MultiFormatReader formatReader = new MultiFormatReader();
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            
            // 将图像数据转换为1 bit data
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            // BinaryBitmap是ZXing用来表示1 bit data位图的类，Reader对象将对它进行解析
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            
            Map<DecodeHintType, String> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            
            // 对图像进行解码
            Result result = formatReader.decode(binaryBitmap, hints);
            contents = result.toString();
        } catch (Exception e) {
            logger.error("解码出错！", e);
        }
        logger.debug("解释二维码文件结束：" + contents);
        return contents;
    }
    
    /**
     * 生成二维码
     */
    public static void encode(String content, int width, int height, File destFile) throws Exception {
        if (!destFile.getParentFile().exists()) {
            if(destFile.mkdirs()) {
                throw new CommonException("创建文件夹失败！");
            }
        }
        String format = "png";// 图像类型  
        Map<EncodeHintType, Object> hint = new HashMap<>();
        hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hint.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint); // 生成矩阵  
        MatrixToImageWriter.writeToPath(bitMatrix, format, destFile.toPath()); // 输出图像  
    }
    
    /**
     * 生成二维码
     */
    public static void encode(String content, int width, int height, OutputStream outputStream) throws Exception {
        String format = "png";// 图像类型  
        Map<EncodeHintType, Object> hint = new HashMap<>();
        hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hint.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint); // 生成矩阵  
        MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
    }
    
    /**
     * 生成二维码
     * @param url 头像地址
     */
    public static void encode(String content, int width, int height, String url, File destFile) {
        try {
            ImageIO.write(genBarcode(content, width, height, url), "jpg", destFile);
        } catch (IOException | WriterException e) {
            logger.error("生成二维码出错！", e);
        }
    }
    
    private static BufferedImage genBarcode(String content, int width, int height, String url) throws WriterException, IOException {
        // 读取源图像  
        BufferedImage scaleImage = scale(url, IMAGE_WIDTH, IMAGE_HEIGHT, true);
        int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
        for (int i = 0;i < scaleImage.getWidth();i++) {
            for (int j = 0;j < scaleImage.getHeight();j++) {
                srcPixels[i][j] = scaleImage.getRGB(i, j);
            }
        }
        
        Map<EncodeHintType, Object> hint = new HashMap<>();
        hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hint.put(EncodeHintType.MARGIN, 1);
        // 生成二维码  
        BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint);
        
        // 二维矩阵转为一维像素数组  
        int halfW = matrix.getWidth() / 2;
        int halfH = matrix.getHeight() / 2;
        int[] pixels = new int[width * height];
        
        for (int y = 0;y < matrix.getHeight();y++) {
            for (int x = 0;x < matrix.getWidth();x++) {
                // 读取图片  
                if (x > halfW - IMAGE_HALF_WIDTH && x < halfW + IMAGE_HALF_WIDTH && y > halfH - IMAGE_HALF_WIDTH && y < halfH + IMAGE_HALF_WIDTH) {
                    pixels[y * width + x] = srcPixels[x - halfW + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
                }
                // 在图片四周形成边框  
                else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                        + IMAGE_HALF_WIDTH + FRAME_WIDTH)
                        || (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)
                        || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                                - IMAGE_HALF_WIDTH + FRAME_WIDTH)
                        || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
                    pixels[y * width + x] = 0xfffffff;
                } else {
                    // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；  
                    pixels[y * width + x] = matrix.get(x, y) ? 0xff000000 : 0xfffffff;
                }
            }
        }
        
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getRaster().setDataElements(0, 0, width, height, pixels);
        
        return image;
    }
    
    /** 
     * 把传入的原始图像按高度和宽度进行缩放，生成符合要求的图标 
     *  
     * @param height 目标高度
     * @param width 目标宽度
     * @param hasFiller 比例不对时是否需要补白：true为补白; false为不补白;
     */
    private static BufferedImage scale(String url, int height, int width, boolean hasFiller) throws IOException {
        double ratio; // 缩放比例
        BufferedImage srcImage = ImageIO.read(new URL(url).openStream());
        Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
        // 计算比例  
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
            if (srcImage.getHeight() > srcImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            destImage = op.filter(srcImage, null);
        }
        if (hasFiller) {// 补白  
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic = image.createGraphics();
            graphic.setColor(Color.white);
            graphic.fillRect(0, 0, width, height);
            if (width == destImage.getWidth(null))
                graphic.drawImage(destImage, 0, (height - destImage.getHeight(null)) / 2, destImage.getWidth(null), destImage.getHeight(null), Color.white, null);
            else
                graphic.drawImage(destImage, (width - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null), destImage.getHeight(null), Color.white, null);
            graphic.dispose();
            destImage = image;
        }
        return (BufferedImage) destImage;
    }
}

class BufferedImageLuminanceSource extends LuminanceSource {
    
    private static final double MINUS_45_IN_RADIANS = -0.7853981633974483; // Math.toRadians(-45.0)
    
    private final BufferedImage image;
    private final int left;
    private final int top;
    
    public BufferedImageLuminanceSource(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
    }
    
    public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
        super(width, height);
        
        if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            this.image = image;
        } else {
            int sourceWidth = image.getWidth();
            int sourceHeight = image.getHeight();
            if (left + width > sourceWidth || top + height > sourceHeight) {
                throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
            }
            
            this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
            
            WritableRaster raster = this.image.getRaster();
            int[] buffer = new int[width];
            for (int y = top;y < top + height;y++) {
                image.getRGB(left, y, width, 1, buffer, 0, sourceWidth);
                for (int x = 0;x < width;x++) {
                    int pixel = buffer[x];
                    
                    // The color of fully-transparent pixels is irrelevant. They
                    // are often, technically, fully-transparent
                    // black (0 alpha, and then 0 RGB). They are often used, of
                    // course as the "white" area in a
                    // barcode image. Force any such pixel to be white:
                    if ((pixel & 0xFF000000) == 0) {
                        pixel = 0xFFFFFFFF; // = white
                    }
                    
                    // .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC),
                    // (306*R) >> 10 is approximately equal to R*0.299, and so
                    // on.
                    // 0x200 >> 10 is 0.5, it implements rounding.
                    buffer[x] = (306 * ((pixel >> 16) & 0xFF) + 601 * ((pixel >> 8) & 0xFF) + 117 * (pixel & 0xFF) + 0x200) >> 10;
                }
                raster.setPixels(left, y, width, 1, buffer);
            }
            
        }
        this.left = left;
        this.top = top;
    }
    
    @Override
    public byte[] getRow(int y, byte[] row) {
        if (y < 0 || y >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
            row = new byte[width];
        }
        // The underlying raster of image consists of bytes with the luminance
        // values
        image.getRaster().getDataElements(left, top + y, width, 1, row);
        return row;
    }
    
    @Override
    public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        // The underlying raster of image consists of area bytes with the
        // luminance values
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }
    
    @Override
    public boolean isCropSupported() {
        return true;
    }
    
    @Override
    public LuminanceSource crop(int left, int top, int width, int height) {
        return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
    }
    
    /**
     * This is always true, since the image is a gray-scale image.
     * @return true
     */
    @Override
    public boolean isRotateSupported() {
        return true;
    }
    
    @Override
    public LuminanceSource rotateCounterClockwise() {
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        
        // Rotate 90 degrees counterclockwise.
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
        
        // Note width/height are flipped since we are rotating 90 degrees.
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
        
        // Draw the original image into rotated, via transformation
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        
        // Maintain the cropped region, but rotate it too.
        int width = getWidth();
        return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
    }
    
    @Override
    public LuminanceSource rotateCounterClockwise45() {
        int width = getWidth();
        int height = getHeight();
        
        int oldCenterX = left + width / 2;
        int oldCenterY = top + height / 2;
        
        // Rotate 45 degrees counterclockwise.
        AffineTransform transform = AffineTransform.getRotateInstance(MINUS_45_IN_RADIANS, oldCenterX, oldCenterY);
        
        int sourceDimension = Math.max(image.getWidth(), image.getHeight());
        BufferedImage rotatedImage = new BufferedImage(sourceDimension, sourceDimension, BufferedImage.TYPE_BYTE_GRAY);
        
        // Draw the original image into rotated, via transformation
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        
        int halfDimension = Math.max(width, height) / 2;
        int newLeft = Math.max(0, oldCenterX - halfDimension);
        int newTop = Math.max(0, oldCenterY - halfDimension);
        int newRight = Math.min(sourceDimension - 1, oldCenterX + halfDimension);
        int newBottom = Math.min(sourceDimension - 1, oldCenterY + halfDimension);
        
        return new BufferedImageLuminanceSource(rotatedImage, newLeft, newTop, newRight - newLeft, newBottom - newTop);
    }
}
